/*
 * @Author: 0x9DEFA478
 * @Date: 2025-10-03 20:49:01
 * @LastEditTime: 2025-10-03 23:31:30
 * @LastEditors: 0x9DEFA478
 * @Description: 
 * 
 */
#include "./Encoding.hpp"




namespace SystemAPI{

  namespace Windows{

#if defined(_WIN32)
    std::string TextEncodeConvert(const std::string& text,UINT srcCP,UINT dstCP)noexcept{
      std::string r;
      
      int wchar_Len;
      int char_Len;
      WCHAR* WCharBuffer=nullptr;
      char* CharBuffer=nullptr;

      do{
        wchar_Len=MultiByteToWideChar(srcCP,0,text.c_str(),-1,nullptr,0);
        if(wchar_Len==0){
          r=text;
          break;
        }

        WCharBuffer=new WCHAR[wchar_Len];
        wchar_Len=MultiByteToWideChar(srcCP,0,text.c_str(),-1,WCharBuffer,wchar_Len);
        if(wchar_Len==0){
          r=text;
          break;
        }

        char_Len=WideCharToMultiByte(dstCP,0,WCharBuffer,-1,nullptr,0,nullptr,nullptr);
        if(char_Len==0){
          r=text;
          break;
        }
        CharBuffer=new char[char_Len];
        char_Len=WideCharToMultiByte(dstCP,0,WCharBuffer,-1,CharBuffer,char_Len,nullptr,nullptr);
        if(char_Len==0){
          r=text;
          break;
        }

        r=std::string(CharBuffer);
      }while(false);

      if(CharBuffer!=nullptr){
        delete[] CharBuffer;
      }
      if(WCharBuffer!=nullptr){
        delete[] WCharBuffer;
      }

      return r;
    }

    std::string TextConvertFromWideString(UINT dstCP,const WCHAR* WideString,int Length)noexcept{
      std::string r;
      int char_Len;
      char* CharBuffer=nullptr;

      char_Len=WideCharToMultiByte(dstCP,0,WideString,Length,nullptr,0,nullptr,nullptr);
      if(char_Len<1){
        return r;
      }

      CharBuffer=new char[char_Len];
      char_Len=WideCharToMultiByte(dstCP,0,WideString,Length,CharBuffer,char_Len,nullptr,nullptr);

      if(char_Len>0){
        r=std::string(CharBuffer);
      }

      if(CharBuffer!=nullptr){
        delete[] CharBuffer;
      }
      return r;
    }

    H::Pointer<WCHAR> TextConvertToWideString(UINT srcCP,const std::string& text)noexcept{
      int wchar_Len;
      H::Pointer<WCHAR> r;

      wchar_Len=MultiByteToWideChar(srcCP,0,text.c_str(),-1,nullptr,0);
      if(wchar_Len<1){
        return r;
      }
      r=r.Array(wchar_Len);
      MultiByteToWideChar(srcCP,0,text.c_str(),-1,&r[0],wchar_Len);
      return r;
    }
#endif

  }
}



